{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "## 2.3 标识符和关键字\n",
    "### 2.3.1 标识符\n",
    "### 命名规则\n",
    "    1.标示符由字母、下划线和数字组成，且数字不能开头。\n",
    "    2.Python中的标识符是区分大小写的。\n",
    "    3.python中的标示符不能使用关键字\n",
    "### 建议\n",
    "    1.见名知意\n",
    "    2.驼峰式\n",
    "    （如：userName,userLoginFlag)"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 2.3.2 关键字\n",
    "    如：>>> help()          # 进入帮助系统\n",
    "       help> keywords      # 查看所有的关键字列表\n",
    "       help> return        # 查看return这个关键字的说明\n",
    "       help> quit          # 退出帮助系统\n"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 2.4 简单数值类型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "整型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "14\n",
      "13\n",
      "61\n",
      "160\n"
     ]
    }
   ],
   "source": [
    "a = 14\n",
    "print(a)\n",
    "a = 0b1101\n",
    "print(a)\n",
    "a = 0o75\n",
    "print(a)\n",
    "a = 0xa0\n",
    "print(a)\n",
    "# 从上到下依次是十进制、二进制、八进制、十六进制"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-27T18:26:31.383779Z",
     "end_time": "2024-11-27T18:26:31.389149Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "浮点型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3140000.0\n"
     ]
    }
   ],
   "source": [
    "a = 3.14e6\n",
    "print(a)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T20:40:52.325315Z",
     "end_time": "2024-10-16T20:40:52.331857Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "布尔类型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "False\n",
      "False\n",
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "a = 0\n",
    "print(bool(a))\n",
    "s = ''\n",
    "print(bool(s))\n",
    "lst = []\n",
    "print(bool(lst))\n",
    "dic = {}\n",
    "print(bool(dic))\n",
    "a = None\n",
    "print(bool(a))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T18:58:50.490229Z",
     "end_time": "2024-10-16T18:58:50.499097Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "复数类型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(5+3j)\n",
      "5.0\n",
      "3.0\n",
      "(2+0j)\n"
     ]
    }
   ],
   "source": [
    "a = 5 + 3j\n",
    "print(a)\n",
    "print(a.real)\n",
    "print(a.imag)\n",
    "b = 2\n",
    "b = complex(b)\n",
    "print(b)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T20:42:18.757347Z",
     "end_time": "2024-10-16T20:42:18.766972Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "数字类型转换"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "2.0\n",
      "(2+0j)\n"
     ]
    }
   ],
   "source": [
    "a = int(3.14)\n",
    "print(a)\n",
    "b = float(2)\n",
    "print(b)\n",
    "c = 2\n",
    "c = complex(c)\n",
    "print(c)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T20:43:39.180379Z",
     "end_time": "2024-10-16T20:43:39.186618Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 2.5 运算符\n",
    "### 2.5.1 赋值运算符"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "1 2\n",
      "3 2\n"
     ]
    }
   ],
   "source": [
    "a = 0\n",
    "a += 1\n",
    "a = a + 1\n",
    "print(a)\n",
    "a, b = 1, 2\n",
    "print(a, b)\n",
    "x = 2\n",
    "y = 3\n",
    "x, y = y, x\n",
    "print(x, y)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T20:46:24.045103Z",
     "end_time": "2024-10-16T20:46:24.053906Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 2.5.2 复合赋值运算符"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 - c的值为： 31\n",
      "2 - c的值为： 52\n",
      "3 - c的值为： 1092\n",
      "4 - c的值为： 52.0\n",
      "5 - c的值为： 2\n",
      "6 - c的值为： 2097152\n",
      "7 - c的值为： 99864\n"
     ]
    }
   ],
   "source": [
    "a = 21\n",
    "b = 10\n",
    "c = 0\n",
    "c = a + b\n",
    "print(\"1 - c的值为：\",c)\n",
    "c += a\n",
    "print(\"2 - c的值为：\",c)\n",
    "c *= a\n",
    "print(\"3 - c的值为：\",c)\n",
    "c /= a\n",
    "print(\"4 - c的值为：\",c)\n",
    "c = 2\n",
    "c %= a\n",
    "print(\"5 - c的值为：\",c)\n",
    "c **= a\n",
    "print(\"6 - c的值为：\",c)\n",
    "c //= a\n",
    "print(\"7 - c的值为：\",c)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T20:50:43.114510Z",
     "end_time": "2024-10-16T20:50:43.134567Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 2.5.3 逻辑运算符"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 - 变量 a 和 b 都为true\n",
      "2 - 变量 a 和 b 都为true，或其中一个变量为true\n",
      "3 - 变量 a 和 b 有一个不为true\n",
      "4 - 变量 a 和 b 都为true，或其中一个变量为true\n",
      "5 - 变量 a 和 b 都为false，或其中一个变量为false\n"
     ]
    }
   ],
   "source": [
    "a = 10\n",
    "b = 20\n",
    "if ( a and b):\n",
    "    print(\"1 - 变量 a 和 b 都为true\")\n",
    "else:\n",
    "    print(\"1 - 变量 a 和 b 有一个不为true\")\n",
    "if ( a or b):\n",
    "    print(\"2 - 变量 a 和 b 都为true，或其中一个变量为true\")\n",
    "else:\n",
    "    print(\"2 - 变量 a 和 b 都不为true\")\n",
    "a = 0\n",
    "if ( a and b ):\n",
    "    print(\"3 - 变量 a 和 b 都为true\")\n",
    "else:\n",
    "    print(\"3 - 变量 a 和 b 有一个不为true\")\n",
    "if ( a or b ):\n",
    "    print(\"4 - 变量 a 和 b 都为true，或其中一个变量为true\")\n",
    "else:\n",
    "    print(\"4 - 变量 a 和 b 都不为true\")\n",
    "if not ( a and b ):\n",
    "    print(\"5 - 变量 a 和 b 都为false，或其中一个变量为false\")\n",
    "else:\n",
    "    print(\"5 - 变量 a 和 b 都为true\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T20:55:52.708301Z",
     "end_time": "2024-10-16T20:55:52.715029Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 2.5.4 成员运算符"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 - 变量 a 不在给定的列表list中\n",
      "2 - 变量 b 不在给定的列表list中\n",
      "3 - 变量 a 在给定的列表list中\n"
     ]
    }
   ],
   "source": [
    "a = 10\n",
    "b = 20\n",
    "list = [1, 2, 3, 4, 5]\n",
    "if ( a in list ):\n",
    "    print(\"1 - 变量 a 在给定的列表list\"\n",
    "          \"中\")\n",
    "else:\n",
    "    print(\"1 - 变量 a 不在给定的列表list中\")\n",
    "if ( b not in list ):\n",
    "    print(\"2 - 变量 b 不在给定的列表list中\")\n",
    "else:\n",
    "    print(\"2 - 变量 b 在给定的列表list中\")\n",
    "# 修改变量a的值\n",
    "a = 2\n",
    "if ( a in list ):\n",
    "    print(\"3 - 变量 a 在给定的列表list\"\n",
    "          \"中\")\n",
    "else:\n",
    "    print(\"3 - 变量 a 不在给定的列表list中\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T20:58:31.820455Z",
     "end_time": "2024-10-16T20:58:31.828072Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 2.6 位运算"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 - c 的值为： 12\n",
      "2 - c 的值为： 61\n",
      "3 - c 的值为： 49\n",
      "4 - c 的值为： -61\n",
      "5 - c 的值为： 240\n",
      "6 - c 的值为： 15\n"
     ]
    }
   ],
   "source": [
    "a = 60 # 60 = 0011 1100\n",
    "b = 13 # 13 = 0000 1101\n",
    "c = 0\n",
    "c = a & b # 12 = 0000 1100\n",
    "print(\"1 - c 的值为：\", c)\n",
    "c = a | b # 61 = 0011 1111\n",
    "print(\"2 - c 的值为：\", c)\n",
    "c = a ^ b # 49 = 0011 0001\n",
    "print(\"3 - c 的值为：\", c)\n",
    "c = ~a # -61 = 1100 0011\n",
    "print(\"4 - c 的值为：\", c)\n",
    "c = a << 2 # 240 = 1111 0000\n",
    "print(\"5 - c 的值为：\", c)\n",
    "c = a >> 2 # 15 = 0000 1111\n",
    "print(\"6 - c 的值为：\", c)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:05:54.109837Z",
     "end_time": "2024-10-16T21:05:54.116704Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 2.7 运算符优先级"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "90.0\n",
      "90.0\n",
      "90.0\n",
      "50.0\n"
     ]
    }
   ],
   "source": [
    "a = 20\n",
    "b = 10\n",
    "c = 15\n",
    "d = 5\n",
    "e = 0\n",
    "e = (a + b) * c / d\n",
    "print(e)\n",
    "e = ((a + b) * c) / d\n",
    "print(e)\n",
    "e = (a + b) * (c / d)\n",
    "print(e)\n",
    "e = a + (b * c) / d\n",
    "print(e)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:08:03.838462Z",
     "end_time": "2024-10-16T21:08:03.844391Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 3 Python流程控制语句\n",
    "## 3.1 判断语句\n",
    "### 3.1.1 if语句\n",
    "### 3.1.2 if...else语句\n",
    "### 3.1.3 if...elif语句\n",
    "### 3.1.4 if嵌套语句"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "welcome boss\n",
      "roadman\n",
      "hello\n",
      "undefine\n",
      "hello\n"
     ]
    }
   ],
   "source": [
    "flag = False\n",
    "name = 'luren'\n",
    "if name == 'luren':\n",
    "    flag = True\n",
    "    print(\"welcome boss\")\n",
    "else:\n",
    "    print(name)\n",
    "num = 5\n",
    "if num == 3:\n",
    "    print(\"boss\")\n",
    "elif num == 2:\n",
    "    print(\"user\")\n",
    "elif num == 1:\n",
    "    print(\"worker\")\n",
    "elif num < 0:\n",
    "    print(\"error\")\n",
    "else:\n",
    "    print(\"roadman\")\n",
    "num = 9\n",
    "if num >= 0 and num <= 10:\n",
    "    print(\"hello\")\n",
    "num = 10\n",
    "if num < 0 or num > 10:\n",
    "    print(\"hello\")\n",
    "else:\n",
    "    print(\"undefine\")\n",
    "nume = 8\n",
    "if ( num >= 0 and num <= 5) or ( num >= 10 and num <= 15):\n",
    "    print(\"hello\")\n",
    "else:\n",
    "    print(\"undefine\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:16:28.844428Z",
     "end_time": "2024-10-16T21:16:28.853435Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 3.2 循环语句\n",
    "### 3.2.1 while语句"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "the count is: 0\n",
      "the count is: 1\n",
      "the count is: 2\n",
      "the count is: 3\n",
      "the count is: 4\n",
      "the count is: 5\n",
      "the count is: 6\n",
      "the count is: 7\n",
      "the count is: 8\n",
      "Good bye!\n"
     ]
    }
   ],
   "source": [
    "count = 0\n",
    "while(count < 9):\n",
    "    print('the count is:', count)\n",
    "    count += 1\n",
    "print(\"Good bye!\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:19:33.127650Z",
     "end_time": "2024-10-16T21:19:33.135716Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.2.2 for语句"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "for letter in \"Python\":\n",
    "    print('当前字母：', letter)\n",
    "fruits = ['banana', 'apple', 'mango']\n",
    "for fruit in fruits:\n",
    "    print('当前水果：', fruit)\n",
    "print(\"Good bye!\")\n",
    "for num in range(10,20):\n",
    "    for i in range(2, num):\n",
    "        if num % i == 0:\n",
    "            j = num / i\n",
    "            print('%d 等于 %d * %d' % (num, i, j))\n",
    "            break\n",
    "    else:\n",
    "        print(num, '是一个质数')"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.2.3 while嵌套"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 是质数\n",
      "3 是质数\n",
      "5 是质数\n",
      "7 是质数\n",
      "11 是质数\n",
      "13 是质数\n",
      "17 是质数\n",
      "19 是质数\n",
      "23 是质数\n",
      "29 是质数\n",
      "31 是质数\n",
      "37 是质数\n",
      "41 是质数\n",
      "43 是质数\n",
      "47 是质数\n",
      "53 是质数\n",
      "59 是质数\n",
      "61 是质数\n",
      "67 是质数\n",
      "71 是质数\n",
      "73 是质数\n",
      "79 是质数\n",
      "83 是质数\n",
      "89 是质数\n",
      "97 是质数\n",
      "Good bye!\n"
     ]
    }
   ],
   "source": [
    "i = 2\n",
    "while i < 100:\n",
    "    j = 2\n",
    "    while j < (i / j):\n",
    "        if not (i % j): break\n",
    "        j += 1\n",
    "    if j > (i / j): print(i, \"是质数\")\n",
    "    i += 1\n",
    "print(\"Good bye!\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:21:48.952666Z",
     "end_time": "2024-10-16T21:21:48.961266Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 3.3 Python的其他语句\n",
    "### 3.3.1 break语句"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-------\n",
      "1\n",
      "-------\n",
      "2\n",
      "-------\n"
     ]
    }
   ],
   "source": [
    "i=1\n",
    "for i in range(5):\n",
    "     i+=1\n",
    "     print(\"-------\")\n",
    "     if i==3:\n",
    "         break\n",
    "     print(i)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:22:48.103898Z",
     "end_time": "2024-10-16T21:22:48.110565Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.2 continue语句"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-------\n",
      "1\n",
      "-------\n",
      "2\n",
      "-------\n",
      "-------\n",
      "4\n",
      "-------\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "i=1\n",
    "for i in range(5):\n",
    "     i+=1\n",
    "     print(\"-------\")\n",
    "     if i==3:\n",
    "         continue\n",
    "     print(i)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:23:15.753276Z",
     "end_time": "2024-10-16T21:23:15.760708Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.3 pass语句"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前字母 : R\n",
      "当前字母 : u\n",
      "当前字母 : n\n",
      "执行 pass 块\n",
      "当前字母 : o\n",
      "执行 pass 块\n",
      "当前字母 : o\n",
      "当前字母 : b\n",
      "Good bye!\n"
     ]
    }
   ],
   "source": [
    "for letter in 'Runoob':\n",
    "   if letter == 'o':\n",
    "      pass\n",
    "      print ('执行 pass 块')\n",
    "   print ('当前字母 :', letter)\n",
    "print (\"Good bye!\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:23:39.417478Z",
     "end_time": "2024-10-16T21:23:39.420844Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.4 else语句"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 is less than 5\n",
      "1 is less than 5\n",
      "2 is less than 5\n",
      "3 is less than 5\n",
      "4 is less than 5\n",
      "5 is not less than 5\n"
     ]
    }
   ],
   "source": [
    "count = 0\n",
    "while count < 5:\n",
    "    print(count, \"is less than 5\")\n",
    "    count += 1\n",
    "else:\n",
    "    print(count, \"is not less than 5\" )"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:25:16.362719Z",
     "end_time": "2024-10-16T21:25:16.365051Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 4 字符串\n",
    "## 4.1 字符串介绍\n",
    "### 4.1.1 转义字符\n",
    "    \\(在行尾时）续行\n",
    "    \\\" 双引号\n",
    "    \\\\ 反斜杠\n",
    "    \\n 换行符\n",
    "    \\t 制表符\n",
    "    \\b 退格符\n",
    "## 4.2 字符串的输出和输入\n",
    "    常见的格式化符号\n",
    "    %s 字符串类型\n",
    "    %d 整数类型\n",
    "    %f 小数类型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 4.2.1 字符串的输出"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "大家好，我叫小明 ,我今年5岁了\n"
     ]
    }
   ],
   "source": [
    "name = '小明'\n",
    "age = 5\n",
    "print(\"大家好，我叫%s ,我今年%d岁了\"%(name,age))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-16T21:31:00.424961Z",
     "end_time": "2024-10-16T21:31:00.458116Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 4.2.2 字符串的输入"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "123\n"
     ]
    }
   ],
   "source": [
    "username = input(\"请输入用户名\")\n",
    "print(username)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T18:37:36.684541Z",
     "end_time": "2024-10-23T18:37:41.923601Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "计算阶乘"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3628800\n"
     ]
    }
   ],
   "source": [
    "num = int(input(\"请输入数字：\"))\n",
    "outcome = 1\n",
    "while(num > 0):\n",
    "    outcome *= num\n",
    "    num -= 1\n",
    "print(outcome)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T18:41:13.894676Z",
     "end_time": "2024-10-23T18:41:17.762735Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 4.3使用切片截取字符串"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abc\n",
      "de\n",
      "bcde\n",
      "cdef\n",
      "fdb\n",
      "fedc\n"
     ]
    }
   ],
   "source": [
    "name = 'abcdef'\n",
    "print(name[0:3])\n",
    "print(name[3:5])\n",
    "print(name[1:-1])\n",
    "print(name[2:])\n",
    "print(name[::-2])\n",
    "print(name[:1:-1])"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T18:44:11.705468Z",
     "end_time": "2024-10-23T18:44:11.710184Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 4.4字符串内建函数\n",
    "find函数：检测字符串是否包括子字符串，返回子字符串的索引位置，如果没有找到，返回-1\n",
    "str.find(string, beg = 0, end = len(str))"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "-1\n"
     ]
    }
   ],
   "source": [
    "name =' abcdef'\n",
    "print(name.find('ab'))\n",
    "print(name.find('ba'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T18:55:10.993448Z",
     "end_time": "2024-10-23T18:55:10.998537Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "index函数：检测字符串是否包括子字符串，返回子字符串的索引位置，如果没有找到，报错\n",
    "str.index(string, beg = 0, end = len(str))"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n"
     ]
    }
   ],
   "source": [
    "name = 'abcdef'\n",
    "print(name.index('ab'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T18:58:34.615491Z",
     "end_time": "2024-10-23T18:58:34.645384Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "replace函数：将旧字符串替换为新字符串，如果max有值，则替换不超过max次\n",
    "str.replace(old, new[,max])"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Abcdef\n"
     ]
    }
   ],
   "source": [
    "name = 'abcdef'\n",
    "print(name.replace('a','A'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:02:25.536604Z",
     "end_time": "2024-10-23T19:02:25.565234Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "count函数：统计字符串中某个字符出现的次数\n",
    "str.count(str, beg = 0, end = len(str))"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "name = 'helloworld'\n",
    "print(name.count('l'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:07:37.788512Z",
     "end_time": "2024-10-23T19:07:37.816455Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "split函数：通过指定分隔符对字符串进行切片，生成列表\n",
    "str.split(str=\"\", num=str.count(string))"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1', '2', '3', '4', '5']\n"
     ]
    }
   ],
   "source": [
    "name = '1,2,3,4,5'\n",
    "print(name.split(','))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:09:22.904553Z",
     "end_time": "2024-10-23T19:09:22.931767Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "capitalize函数：将字符串的第一个字符大写，其余小写\n",
    "str.capitalize()\n",
    "titles函数：将字符串中每个单词的首字母大写，其余小写\n",
    "str.title()"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello world\n",
      "Hello World\n"
     ]
    }
   ],
   "source": [
    "name = 'hello world'\n",
    "print(name.capitalize())\n",
    "print(name.title())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:14:12.393817Z",
     "end_time": "2024-10-23T19:14:12.406838Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "startswith函数：检查字符串是否以指定子串开头，如果是返回True，否则返回False\n",
    "str.startswith(str, beg = 0, end = len(str))"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "name = 'helloworld'\n",
    "print(name.startswith('hello'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:13:35.710324Z",
     "end_time": "2024-10-23T19:13:35.758661Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "endswith函数：检查字符串是否以指定子串结尾，如果是返回True，否则返回False\n",
    "str.endswith(suffix[,start[,end]])"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "name = 'helloworld'\n",
    "print(name.endswith('world'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:25:32.205244Z",
     "end_time": "2024-10-23T19:25:32.210259Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "upper函数：将字符串中的小写字母转换为大写字母\n",
    "str.upper()\n",
    "lower函数：将字符串中的大写字母转换为小写字母\n",
    "str.lower()"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "HELLO WORLD\n",
      "hello world\n"
     ]
    }
   ],
   "source": [
    "name = 'hello world'\n",
    "print(name.upper())\n",
    "name = 'HELLO WORLD'\n",
    "print(name.lower())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-24T17:42:08.374497Z",
     "end_time": "2024-10-24T17:42:08.379912Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "ljust函数：左对齐，并用空格填充至指定长度的新字符串\n",
    "str.ljust(width[,fillchar])"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello*****\n"
     ]
    }
   ],
   "source": [
    "name = 'hello'\n",
    "print(name.ljust(10,'*'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:33:53.719844Z",
     "end_time": "2024-10-23T19:33:53.726177Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "rjust函数：右对齐，并用空格填充至指定长度的新字符串\n",
    "str.rjust(width[,fillchar])"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "*****hello\n"
     ]
    }
   ],
   "source": [
    "name = 'hello'\n",
    "print(name.rjust(10,'*'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:33:55.739103Z",
     "end_time": "2024-10-23T19:33:55.745627Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "center函数：居中，并用空格填充至指定长度的新字符串\n",
    "str.center(width[,fillchar])"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "**hello***\n"
     ]
    }
   ],
   "source": [
    "name = 'hello'\n",
    "print(name.center(10,'*'))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:34:17.290938Z",
     "end_time": "2024-10-23T19:34:17.328854Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "lstrip函数：删除字符串左边的空格或指定字符\n",
    "str.lstrip([chars])"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n"
     ]
    }
   ],
   "source": [
    "name = '    hello'\n",
    "print(name.lstrip())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:37:15.227978Z",
     "end_time": "2024-10-23T19:37:15.236136Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "strip函数：删除字符串左右两边的空格或指定字符\n",
    "str.strip([chars])"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n"
     ]
    }
   ],
   "source": [
    "name = '   hello   '\n",
    "print(name.strip())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:38:22.424670Z",
     "end_time": "2024-10-23T19:38:22.432176Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 4.5字符串运算符\n",
    "    + 连接字符串\n",
    "    * 重复字符串\n",
    "    [] 提取字符\n",
    "    [:] 切片\n",
    "    in 检测字符串是否包含子串\n",
    "    not in 检测字符串是否不包含子串\n",
    "    r/R 字符串格式化"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abcd\n",
      "efg\n",
      "abcd\\nefg\n"
     ]
    }
   ],
   "source": [
    "str = 'abcd\\nefg'\n",
    "print(str)\n",
    "print(r'abcd\\nefg')"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T19:41:32.217045Z",
     "end_time": "2024-10-23T19:41:32.224145Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 5 列表，元组和字典\n",
    "## 5.1 列表概述\n",
    "    1.列表是Python中的一种数据结构，它可以存储不同类型的数据\n",
    "    2.列表索引是从0开始的，我们可以通过下标索引的方式来访问列表中的值。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "xiaoWang\n",
      "xiaoZhang\n"
     ]
    }
   ],
   "source": [
    "A = [1,'xiaoWang','a', [2, 'b']]\n",
    "A = ['xiaoWang', 'xiaoZhang', 'xiaoHua']\n",
    "print(A[0])\n",
    "print(A[1])"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-25T16:14:16.752432Z",
     "end_time": "2024-10-25T16:14:16.757313Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.2列表的循环遍历\n",
    "### 5.2.1 for循环遍历"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "xiaoWang\n",
      "xiaoZhang\n",
      "xiaoHua\n"
     ]
    }
   ],
   "source": [
    "namesList = ['xiaoWang', 'xiaoZhang', 'xiaoHua']\n",
    "for i in namesList:\n",
    "    print(i)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-25T16:15:28.469649Z",
     "end_time": "2024-10-25T16:15:28.478173Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.2.2 while循环遍历"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "xiaoWang\n",
      "xiaoZhang\n",
      "xiaoHua\n"
     ]
    }
   ],
   "source": [
    "namesList = ['xiaoWang', 'xiaoZhang', 'xiaoHua']\n",
    "length = len(namesList)\n",
    "i = 0\n",
    "while i < length:\n",
    "    print(namesList[i])\n",
    "    i += 1"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-25T16:19:11.104484Z",
     "end_time": "2024-10-25T16:19:11.112196Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.3 列表的常见操作\n",
    "append函数：向列表末尾添加元素"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4]\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "a.append(4)\n",
    "print(a)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T20:00:16.065949Z",
     "end_time": "2024-10-23T20:00:16.073339Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "extend函数：向列表末尾添加元素，与append不同的是，可以添加多个元素"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 6]\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "b = [4,5,6]\n",
    "a.extend(b)\n",
    "print(a)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-23T20:02:02.744366Z",
     "end_time": "2024-10-23T20:02:02.753050Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "insert函数：在列表指定位置插入元素"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, [4, 5, 6], 2, 3]\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "b = [4,5,6]\n",
    "a.insert(1, b)\n",
    "print(a)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-31T09:34:43.114821Z",
     "end_time": "2024-10-31T09:34:43.133649Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 5, 6, 2, 3]\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "b = [4,5,6]\n",
    "count = len(b)\n",
    "for i in range(0,count,1):\n",
    "    a.insert(i+1, b[i])\n",
    "print(a)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-31T09:35:49.932319Z",
     "end_time": "2024-10-31T09:35:49.950797Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1860724342144\n",
      "1860724342144\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "b = a\n",
    "b[0] = 4\n",
    "print(id(a))\n",
    "print(id(b))\n",
    "# 二者内存地址相同，修改其中一个，另一个也会被修改"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-30T19:19:00.078151Z",
     "end_time": "2024-10-30T19:19:00.085013Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "pop函数：删除列表指定位置的元素，默认删除最后一个元素"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3,4,5]\n",
    "a.pop(2)\n",
    "print(a)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-30T19:21:53.142110Z",
     "end_time": "2024-10-30T19:21:53.151749Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "remove函数：删除列表中指定的元素的值"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 4, 5]\n",
      "[2, 3, 1, 5]\n",
      "[2, 3, 5]\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3,4,5]\n",
    "a.remove(3)\n",
    "print(a)\n",
    "b = [1,2,3,1,5]\n",
    "b.remove(1)\n",
    "print(b)\n",
    "c = [1,2,3,1,5]\n",
    "while 1 in c:\n",
    "    c.remove(1)\n",
    "print(c)\n",
    "# 将字典中的元素1全部删除"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-30T19:41:36.244328Z",
     "end_time": "2024-10-30T19:41:36.257098Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n",
      "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
      "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n"
     ]
    }
   ],
   "source": [
    "a = [i for i in range(9, -1, -1)]\n",
    "print(a)\n",
    "a.sort()\n",
    "print(a)\n",
    "a.reverse()\n",
    "print(a)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-30T19:27:50.008707Z",
     "end_time": "2024-10-30T19:27:50.017466Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.4元组的相关操作\n",
    "### 5.4.1 访问元组"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "100\n",
      "4.5\n"
     ]
    }
   ],
   "source": [
    "tuple=('hello',100,4.5)\n",
    "print(tuple[0])\n",
    "print(tuple[1])\n",
    "print(tuple[2])"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-31T09:40:04.074907Z",
     "end_time": "2024-10-31T09:40:04.104483Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.4.2 元组不允许修改元素"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "tup1 = (12,34,56)\n",
    "tup2 = ('abc', 'xyz')\n",
    "# 以下修改元组元素操作是非法的。\n",
    "tup1[0] = 100\n",
    "tup2[0] = 100"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.4.3 遍历元组"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "a = tuple([1, 2, 3])\n",
    "for i in a:\n",
    "    print(i)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-31T09:31:54.204242Z",
     "end_time": "2024-10-31T09:31:54.216067Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.4.4元组的内置函数：\n",
    "    len(tuple)：返回元组中元素的个数\n",
    "    max(tuple)：返回元组中元素最大值\n",
    "    min(tuple)：返回元组中元素最小值\n",
    "    tuple(seq)：将列表转换为元组"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "3\n",
      "1\n",
      "[1, 2, 3]\n"
     ]
    }
   ],
   "source": [
    "a = (1, 2, 3)\n",
    "print(len(a))\n",
    "print(max(a))\n",
    "print(min(a))\n",
    "b = ([1, 2, 3])\n",
    "print(b)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-31T09:45:34.738262Z",
     "end_time": "2024-10-31T09:45:34.757048Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.5 字典的常见操作\n",
    "### 5.5.1 根据键访问值\n",
    "### 5.5.2 修改字典的元素\n",
    "### 5.5.3 添加字典的元素"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "班长\n",
      "北京\n",
      "None\n",
      "{'name': '班长', 'id': 101, 'sex': 'female', 'address': '北京'}\n",
      "{'name': '班长', 'id': 101, 'sex': 'female', 'address': '北京', 'age': 18}\n"
     ]
    }
   ],
   "source": [
    "info = {'name':'班长', 'id':100, 'sex':'female','address':'北京'}\n",
    "print(info['name'])\n",
    "print(info['address'])\n",
    "age = info.get('age')\n",
    "print(age)\n",
    "newid = 101\n",
    "info['id'] = newid\n",
    "print(info)\n",
    "info['age'] = 18\n",
    "print(info)"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.5.4 删除字典的元素\n",
    "    clear函数：清空字典，但是字典仍保留\n",
    "    pop函数：删除字典中指定的键值对"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{}\n",
      "{'id': 100, 'sex': 'female', 'address': '北京'}\n"
     ]
    }
   ],
   "source": [
    "info = {'name':'班长', 'id':100, 'sex':'female','address':'北京'}\n",
    "info.clear()\n",
    "print(info)\n",
    "info = {'name':'班长', 'id':100, 'sex':'female','address':'北京'}\n",
    "info.pop('name')\n",
    "print(info)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-31T09:50:05.046930Z",
     "end_time": "2024-10-31T09:50:05.055379Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.5.5 计算字典中的键值对的个数\n",
    "### 5.5.6 获取字典中的所有键\n",
    "### 5.5.7 获取字典中的所有值\n",
    "### 5.5.8 获取字典中的所有键值对"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['Name', 'Age'])\n",
      "dict_values(['Zara', 7])\n",
      "dict_items([('Name', 'Zara'), ('Age', 7)])\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name':'Zara', 'Age':7}\n",
    "print(dict.keys())\n",
    "print(dict.values())\n",
    "print(dict.items())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-30T19:51:52.536882Z",
     "end_time": "2024-10-30T19:51:52.548805Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.6 字典的遍历\n",
    "### 5.6.1 遍历字典的键\n",
    "### 5.6.2 遍历字典的值\n",
    "### 5.6.3 遍历字典的元素\n",
    "### 5.6.4 遍历字典的键值对"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name Zara\n",
      "Age 7\n",
      "Zara\n",
      "7\n",
      "Name\n",
      "Age\n",
      "key=Name，value=Zara\n",
      "key=Age，value=7\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name':'Zara', 'Age':7}\n",
    "for key, value in dict.items():\n",
    "    print(key, value)\n",
    "for _ , value in dict.items():\n",
    "    print(value)\n",
    "for key, _ in dict.items():\n",
    "    print(key)\n",
    "for key,value in dict.items():          print(\"key=%s，value=%s\"%(key,value))\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-31T09:54:13.092979Z",
     "end_time": "2024-10-31T09:54:13.105232Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 6 函数\n",
    "## 6.1 什么是函数\n",
    "       函数是组织好的，可重复使用的，用来实现单一或相关联功能的代码段，它能够提高应用的模块性和代码的重复利用率。\n",
    "## 6.2 函数的定义和调用\n",
    "       def 函数名（参数列表）:\n",
    "           函数体\n",
    "       定义了函数之后，想要让这些代码能够执行，需要调用函数。通过“函数名()” 即可完成调用。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------------------------------------\n",
      "         生命苦短，我用Python            \n",
      "------------------------------------\n"
     ]
    }
   ],
   "source": [
    "def printInfo():\n",
    "    print('------------------------------------')\n",
    "    print('         生命苦短，我用Python            ')\n",
    "    print('------------------------------------')\n",
    "printInfo()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-10-31T09:57:44.035672Z",
     "end_time": "2024-10-31T09:57:44.057155Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6.3 函数的参数\n",
    "### 6.3.1 函数的返回值\n",
    "    如果希望定义的函数，可以计算任何两个数和，我们在定义函数的时候，让函数接收数据，这就是函数的参数"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "33\n"
     ]
    }
   ],
   "source": [
    "def add2num(a, b):\n",
    "    c = a+b\n",
    "    print(c)\n",
    "add2num(11, 22)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-06T22:21:14.426264Z",
     "end_time": "2024-11-06T22:21:14.439016Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 6.3.2 默认参数\n",
    "    调用函数时，如果没有传递参数，则会使用默认参数"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name:  miki\n",
      "Age: 35\n",
      "Name:  miki\n",
      "Age: 9\n"
     ]
    }
   ],
   "source": [
    "def printinfo( name, age = 35 ):\n",
    "    print('Name: ',name)\n",
    "    print('Age:' ,age)\n",
    "printinfo(name=\"miki\" )\n",
    "printinfo(age=9,name=\"miki\" )"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-06T22:24:07.251443Z",
     "end_time": "2024-11-06T22:24:07.284105Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 6.3.3 不定长参数\n",
    "    有时可能需要一个函数能处理比当初声明时更多的参数，这些参数叫做不定长参数，声明时不会命名"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 2 3 4 5 6 7 8 9\n"
     ]
    }
   ],
   "source": [
    "def func(a,b,*args,**kwargs):\n",
    "    print(a,b,*args,**kwargs)\n",
    "func(1,2)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-13T18:33:49.531313Z",
     "end_time": "2024-11-13T18:33:49.548851Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6.4 函数的返回值\n",
    "    函数的返回值是使用return语句来完成的"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "def add2num(a, b):\n",
    "    c = a+b\n",
    "    return c"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6.5 函数的四种类型\n",
    "    无参数，无返回值的函数\n",
    "    无参数，有返回值的函数\n",
    "    有参数，无返回值的函数\n",
    "    有参数，有返回值的函数\n"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------\n",
      "      xx涮涮锅 点菜系统\n",
      "  1.  羊肉涮涮锅\n",
      "  2.  牛肉涮涮锅\n",
      "  3.  猪肉涮涮锅\n",
      "--------------------------\n",
      "当前的温度为: 24\n"
     ]
    }
   ],
   "source": [
    "def printMenu():\n",
    "        print('--------------------------')\n",
    "        print('      xx涮涮锅 点菜系统')\n",
    "        print('  1.  羊肉涮涮锅')\n",
    "        print('  2.  牛肉涮涮锅')\n",
    "        print('  3.  猪肉涮涮锅')\n",
    "        print('--------------------------')\n",
    "printMenu()\n",
    "def getTemperature():\n",
    "    return 24\n",
    "temperature = getTemperature()\n",
    "print('当前的温度为:',temperature)\n",
    "def test(num1,num2):\n",
    "       result=num1+num2\n",
    "       print('计算结果为：%d'%result)\n",
    "def calculateNum(num):\n",
    "    result = 0\n",
    "    i = 1\n",
    "    while i<=num:\n",
    "        result = result + i\n",
    "        i+=1\n",
    "        return result\n",
    "    result = calculateNum(100)\n",
    "    print('1~100的累积和为:', result)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-06T22:27:58.872430Z",
     "end_time": "2024-11-06T22:27:58.887005Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6.6 函数的嵌套调用"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "a = 3\n",
    "def aaa():\n",
    "    global a\n",
    "    a = 5\n",
    "    print(a)\n",
    "aaa()\n",
    "print(a)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-06T19:41:51.913459Z",
     "end_time": "2024-11-06T19:41:51.927544Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6.7 变量的作用域\n",
    "### 6.7.1 作用域\n",
    "    为了避免变量的名称发生冲突，所以Python引入了命名空间的概念。\n",
    "    命名空间指的是名称到对象的映射，类似于字典，键名是变量的名字，值是变量的值。\n",
    "    命名空间是相互独立存在的，而且它们被安排在某个特定的层次，把这些层次结构组合起来就是作用域。\n",
    "    本地作用域\n",
    "    函数嵌套作用域\n",
    "    文件作用域\n",
    "    内置作用域\n",
    "### 6.7.2 局部变量\n",
    "    所谓局部变量，就是在函数内部定义的变量。\n",
    "    局部变量的作用域是函数内部，意味着它只在定义它的函数中有效，一旦函数结束就会消失\n",
    "### 6.7.3 全局变量\n",
    "    定义在函数外的拥有全局作用域。\n",
    "    全局变量可以在整个程序范围内访问。\n",
    "    如果出现全局变量和局部变量名字相同的情况，则在函数中访问的是局部变量。\n"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6.8 递归函数和匿名函数\n",
    "### 6.8.1 递归函数\n",
    "    一个函数的内部可以调用其他函数。但是，如果一个函数在内部不调用其它的函数，而是自己本身的话，这个函数就是递归函数。\n"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "a = int(input())\n",
    "result = 1\n",
    "while a > 0:\n",
    "    result = result * a\n",
    "    a-=1\n",
    "print(result)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-06T19:45:53.317427Z",
     "end_time": "2024-11-06T19:45:54.552160Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 6.8.2 匿名函数\n",
    "    匿名函数就是没有名称的函数，也就是不再使用def语句定义的函数。如果要声明匿名函数，则需要使用lambda关键字，匿名函数的声明格式如下所示：\n",
    "    lambda 参数列表:表达式"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "相加的结果为： 30\n",
      "相加的结果为： 40\n"
     ]
    }
   ],
   "source": [
    "sum = lambda arg1, arg2: arg1 + arg2\n",
    "print(\"相加的结果为：\",sum(10,20))\n",
    "print(\"相加的结果为：\",sum(20,20))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-13T18:56:50.835593Z",
     "end_time": "2024-11-13T18:56:50.899640Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6.9 日期时间函数\n",
    "### 6.9.1 时间函数\n",
    "    在python中，通常有如下几种方式表示时间：\n",
    "    1.时间戳(1970-1-1 00:00:00)\n",
    "    2.格式化的时间字符串\n",
    "    3.时间元组（struct_time）"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前时间戳为: 1731584940.941545\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "ticks = time.time()\n",
    "print(\"当前时间戳为:\", ticks)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T19:49:00.940547Z",
     "end_time": "2024-11-14T19:49:00.955764Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "可以使用time模块的strftime方法来格式化日期:\n",
    "    %Y  4位数的年份表示（0000-9999）\n",
    "    %y  2位数的年份表示（00-99）\n",
    "    %m  月份（01-12）\n",
    "    %d  月份中的天数（1-31）\n",
    "    %H  24小时制小时数（0-23）\n",
    "    %M  分（00-59）\n",
    "    %S  秒（00-59）\n",
    "    %l  小写的am/pm"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-11-14 19:50:38\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T19:50:38.812744Z",
     "end_time": "2024-11-14T19:50:38.833834Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "时间元组：\n",
    "返回struct_time的函数主要有gmtime()、localtime()和strptime()，struct_time元组。\n",
    "tm_year   年份\n",
    "tm_mon   月份（1-12）\n",
    "tm_mday   月份中的天数（1-31）\n",
    "tm_hour  24小时制小时数（0-23）\n",
    "tm_min   分（00-59）\n",
    "tm_sec   秒（00-59）\n",
    "tm_wday   星期几（0-6）\n",
    "tm_yday   从1月1日到当前日期的天数（1-366）\n",
    "tm_isdst  是否为夏令时\n",
    "time.altzone  夏令时秒数\n",
    "time.asctime([tupletime])  接受时间元组并返回一个可读的形式为\"Tue Dec 11 18:07:14 2008\"（2008年12月11日周二18时07分14秒）的24个字符的字符串。\n",
    "time.clock( )  用以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时，比time.time()更有用。\n",
    "time.ctime([secs]) 作用相当于asctime(localtime(secs))，未给参数相当于asctime()。\n",
    "time.gmtime([secs]) 接收时间辍（1970纪元后经过的浮点秒数）并返回格林威治天文时间下的时间元组t。\n",
    "time.localtime([secs]) 接收时间辍（1970纪元后经过的浮点秒数）并返回当地时间下的时间元组t（t.tm_isdst可取0或1，取决于当地当时是不是夏令时）\n",
    "time.mktime(tupletime) 接受时间元组并返回时间戳\n",
    "time.sleep(secs) 推迟调用线程的运行，secs指秒数。\n",
    "time.strftime(fmt[,tupletime]) 接收以时间元组，并返回以可读字符串表示的当地时间，格式由fmt决定。\n",
    "time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') 根据fmt的格式把一个时间字符串解析为时间元组。\n",
    "time.time( ) 返回当前时间的时间戳\n",
    "time.tzset() 根据环境变量TZ重新初始化时间相关设置。\n",
    "time.timezone 表示当地时区（未启动夏令时）距离格林威治的偏移秒数（>0，美洲;<=0大部分欧洲，亚洲，非洲）\n",
    "time.tzname 包含一对根据情况的不同而不同的字符串，分别是带夏令时的本地时区名称，和不带的。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 6.9.2 日历函数\n",
    "    calendar.calendar(year,w=2,l=1,c=6) 返回一个多行字符串格式的year年年历，3个月一行，间隔距离为c。每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。\n",
    "    calendar. firstweekday() 返回当前每周起始日期的设置。默认情况下，首次载入caendar模块时返回0，即星期一。\n",
    "    calendar.isleap(year)  如果是闰年返回True，否则为false。\n",
    "    calendar.leapdays(y1,y2) 返回在Y1，Y2两年之间的闰年总数。\n",
    "    calendar.month(year,month,w=2,l=1) 返回一个多行字符串格式的year年month月日历，两行标题，一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。\n",
    "    calendar.monthrange(year,month) 返回两个整数。第一个是该月的星期几的日期码，第二个是该月的日期码。日从0（星期一）到6（星期日）;月从1到12。\n",
    "    calendar.prcal(year,w=2,l=1,c=6) 相当于print(calendar.calendar(year,w,l,c))\n",
    "    calendar.setfirstweekday(weekday) 设置每周的起始日期码。0（星期一）到6（星期日）\n",
    "    calendar.prmonth(year,month,w=2,l=1) 相当于 print(calendar.calendar（year，w，l，c））\n",
    "    calendar.timegm(tupletime) 和time.gmtime相反：接受一个时间元组形式，返回该时刻的时间辍（1970纪元后经过的浮点秒数）\n",
    "    calendar.weekday(year,month,day) 返回给定日期的日期码。0（星期一）到6（星期日）。月份为 1（一月） 到 12（12月）。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6.10 随机数函数"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "random.random() 用于生成一个0到1的随机符点数: 0 <= n < 1.0。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "random(): 0.779257516666948\n",
      "random(): 0.47594202865129187\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "print(\"random():\", random.random())\n",
    "print(\"random():\", random.random())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T20:04:43.175722Z",
     "end_time": "2024-11-14T20:04:43.189688Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "random.uniform(a,b) 返回a,b之间的随机浮点数，范围[a,b]或[a,b]取决于四舍五入，a不一定要比b小。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "random: 51.369959462361436\n",
      "random: 75.88314863964743\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "print(\"random:\",random.uniform(50,100))\n",
    "print(\"random:\",random.uniform(100,50))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T20:06:00.053281Z",
     "end_time": "2024-11-14T20:06:00.069867Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "random.randint(a,b) 返回a,b之间的整数，范围[a,b]，注意：传入参数必须是整数，a一定要比b小"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "print(random.randint(12,20))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T20:06:31.584272Z",
     "end_time": "2024-11-14T20:06:31.602134Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "random.randrang([start], stop[, step]) 返回有个区间内的整数，可以设置step。只能传入整数，random.randrange(10, 100, 2)，结果相当于从[10, 12, 14, 16, … 96, 98]序列中获取一个随机数。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "print(random.randrange(10, 100, 2))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T20:07:20.718623Z",
     "end_time": "2024-11-14T20:07:20.735012Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "random.choice(sequence) 从sequence（序列，是有序类型的）中随机获取一个元素，列表、元组、字符串都属于sequence。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [
    {
     "data": {
      "text/plain": "40"
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import random\n",
    "random.choice(range(10,100,2))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T20:08:58.861499Z",
     "end_time": "2024-11-14T20:08:58.878445Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "random.shuffle(x[,random]) 用于将列表中的元素打乱顺序，俗称为洗牌。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [],
   "source": [
    "import random\n",
    "p = [\"Python\",\"is\", \"powerful\", \"simple\"]\n",
    "random.shuffle(p)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T20:09:24.324124Z",
     "end_time": "2024-11-14T20:09:24.339108Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "random.sample(sequence,k) 从指定序列中随机获取k个元素作为一个片段返回，sample函数不会修改原有序列"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[4, 6, 10, 3, 1]\n",
      "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n",
    "slice = random.sample(list, 5)\n",
    "print(slice)\n",
    "print(list)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T20:10:01.897968Z",
     "end_time": "2024-11-14T20:10:01.915579Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 7 高级函数\n",
    "## 7.1 闭包\n",
    "    闭包指的是函数嵌套函数，并且内层函数引用了外层函数的变量，并且外层函数返回内层函数。\n",
    "    需要满足3个条件：\n",
    "    1.存在于两个嵌套关系的函数中，并且闭包是内部函数\n",
    "    2.内部函数引用了外部函数的变量（自由变量）\n",
    "    3.外部函数会把内部函数的函数名称返回"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n"
     ]
    }
   ],
   "source": [
    "def outer(start=0):\n",
    "    count = [start]\n",
    "    def inner():\n",
    "        count[0] += 1\n",
    "        return count[0]\n",
    "    return inner\n",
    "out = outer(5)\n",
    "print(out())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-14T19:44:46.958688Z",
     "end_time": "2024-11-14T19:44:46.965257Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 7.2 装饰器\n",
    "    装饰器是一种特殊的函数，它接收一个函数作为参数，返回一个函数。\n",
    "    装饰器可以用来修改函数的功能，也可以用来添加新的功能。\n",
    "    装饰器主要应用在如下场景：\n",
    "    引入日志、函数执行时间统计、执行函数前预备处理、执行函数后清理功能、权限校验、缓存\n",
    "    通过在函数定义的前面添加@符号和装饰器名，实现装饰器对函数的包装。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test函数执行完毕\n",
      "函数执行时间： 1.0009896755218506\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "def spendtime(func):\n",
    "    def inner():\n",
    "        starttime = time.time()\n",
    "        func()\n",
    "        print('函数执行时间：',time.time()-starttime)\n",
    "    return inner\n",
    "@spendtime\n",
    "def test():\n",
    "    time.sleep(1)\n",
    "    print('test函数执行完毕')\n",
    "test()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-13T20:04:45.963534Z",
     "end_time": "2024-11-13T20:04:46.971582Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 7.3 常见python内置函数"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "map函数：map(function, iterable, ...)\n",
    "第一个参数是函数的名称，第二个参数是可迭代对象，可迭代对象可以是一个列表、元组、字典、字符串等。\n",
    "map函数接收一个函数和可迭代对象，返回一个迭代器，迭代器中包含的是函数对可迭代对象中每个元素进行操作的结果。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 4, 5, 6, 7]\n"
     ]
    }
   ],
   "source": [
    "func = lambda x:x+2\n",
    "result = map(func, [1,2,3,4,5])\n",
    "print(list(result))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:39:51.611565Z",
     "end_time": "2024-11-21T19:39:51.618923Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "filter函数：filter(function, iterable)\n",
    "第一个参数是函数的名称，第二个参数是可迭代对象，可迭代对象可以是一个列表、元组、字典、字符串等。\n",
    "fliter函数对指定序列执行过滤操作"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 3, 5]\n"
     ]
    }
   ],
   "source": [
    "func = lambda x:x%2\n",
    "result = filter(func, [1, 2, 3, 4, 5])\n",
    "print(list(result))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:40:09.322459Z",
     "end_time": "2024-11-21T19:40:09.343613Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 8 文件操作\n",
    "## 8.1 文件的打开和关闭\n",
    "    open(文件名,模式)\n",
    "    模式：\n",
    "    r：只读模式，文件必须存在，默认模式\n",
    "    w：只写模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    a：追加模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    rb ：二进制只读模式，文件必须存在，默认模式\n",
    "    wb ：二进制只写模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    ab：二进制追加模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    r+：读写模式，文件必须存在，如果文件不存在，则报错\n",
    "    w+：读写模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    a+：读写模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    rb+：二进制读写模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    wb+ ：二进制读写模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    ab+ ：二进制读写模式，文件必须存在，如果文件不存在，则创建文件\n",
    "    U： universal newline模式，自动处理换行符\n",
    "    f.close()"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12345\n",
      "课程\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "fp = open('test.txt','r',encoding='utf-8')\n",
    "print(fp.read())\n",
    "fp.close()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:58:58.008460Z",
     "end_time": "2024-11-21T19:58:58.036278Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 8.2 文件的读写\n",
    "### 8.2.1 写文件\n",
    "    向文件写数据，需要使用write方法来完成，在操作某个文件时，每调用一次write方法，写入的数据就会追加到文件末尾。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [],
   "source": [
    "f = open('itheima.txt', 'w')\n",
    "f.write('hello itheima, i am here!')\n",
    "f.close()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:46:00.607471Z",
     "end_time": "2024-11-21T19:46:00.670300Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.2.2 读文件"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "方法1：使用read方法读取文件"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello itheim\n",
      "------------------------------\n",
      "a, i am here!\n"
     ]
    }
   ],
   "source": [
    "f = open('itheima.txt', 'r')\n",
    "content = f.read(12)\n",
    "print(content)\n",
    "print(\"-\"*30)\n",
    "content = f.read()\n",
    "print(content)\n",
    "f.close()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:46:16.976819Z",
     "end_time": "2024-11-21T19:46:17.001973Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "方法2：使用readlines方法读取文件"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1:hello itheima, i am here!\n"
     ]
    }
   ],
   "source": [
    "f= open('itheima.txt', 'r')\n",
    "content = f.readlines()\n",
    "i = 1\n",
    "for temp in content:\n",
    "     print(\"%d:%s\" % (i, temp))\n",
    "     i += 1\n",
    "f.close()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:48:13.174203Z",
     "end_time": "2024-11-21T19:48:13.204332Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "方法3：使用readline方法一行一行读数据"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1:hello itheima, i am here!\n",
      "\n",
      "2:hello itheima, i am here!\n"
     ]
    }
   ],
   "source": [
    "f = open('itheima.txt', 'r')\n",
    "content = f.readline()\n",
    "print(\"1:%s\"%content)\n",
    "content = f.readline()\n",
    "print(\"2:%s\"%content)\n",
    "f.close()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:49:21.600730Z",
     "end_time": "2024-11-21T19:49:21.633551Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.2.3 文件的定位读写"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "方法1：使用tell方法来获取文件当前的读写位置"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "读取的数据是 :  hell\n",
      "当前文件位置 :  4\n"
     ]
    }
   ],
   "source": [
    "f = open(\"itheima.txt\", \"r\")\n",
    "str = f.read(4)\n",
    "print('读取的数据是 : ', str)\n",
    "position = f.tell()\n",
    "print(\"当前文件位置 : \", position)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:51:33.674232Z",
     "end_time": "2024-11-21T19:51:33.706521Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "方法2：使用seek方法来移动文件读取指针到指定位置\n",
    "seek(offset, from)方法包含两个参数：\n",
    "offset:表示偏移量，也就是代表需要移动偏移的字节数\n",
    "from:表示方向，可以指定从哪个位置开始偏移\n",
    "0:表示文件开头（默认值）\n",
    "1:表示当前位置\n",
    "2:表示文件末尾"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello itheima, i am here!\n",
      "hello itheima, i am here!\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "f = open(\"itheima.txt\", \"r\")\n",
    "f.seek(0, 0)\n",
    "print(f.read())\n",
    "f.seek(0, 1)\n",
    "print(f.read())\n",
    "f.seek(0, 2)\n",
    "print(f.read())\n",
    "f.close()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:52:33.564800Z",
     "end_time": "2024-11-21T19:52:33.587606Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 8.3 文件的重命名和删除\n",
    "### 8.3.1 文件的重命名\n",
    "    os.rename(需要修改的文件名, 新的文件名)\n",
    "### 8.3.2 文件的删除\n",
    "    os.remove(待删除的文件名)"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 8.4 文件的相关操作\n",
    "### 8.4.1 创建文件夹"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [],
   "source": [
    "import os\n",
    "os.mkdir(\"张三\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:54:53.695877Z",
     "end_time": "2024-11-21T19:54:53.717972Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.4.2 获取当前目录"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [
    {
     "data": {
      "text/plain": "'D:\\\\WorkSpace\\\\python2024\\\\lesson-8'"
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "os.getcwd()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:55:50.537845Z",
     "end_time": "2024-11-21T19:55:50.574804Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.4.3 改变默认目录\n",
    "    import os\n",
    "    os.chdir(\"../”)"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.4.4 获取目录列表"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [
    {
     "data": {
      "text/plain": "['itheima.txt', 'test.txt', '张三', '课堂笔记.ipynb']"
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "os.listdir (\"./\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T19:57:17.772926Z",
     "end_time": "2024-11-21T19:57:17.803605Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.4.5 删除文件夹\n",
    "    import os\n",
    "    os.rmdir (”张三”)"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12345\n",
      "\n",
      "课程\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "fp = open('test.txt','r',encoding='utf-8')\n",
    "for line in fp:\n",
    "    print(line)\n",
    "fp.close()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-20T19:49:13.232413Z",
     "end_time": "2024-11-20T19:49:13.249624Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 9 异常处理\n",
    "## 9.1 异常简介\n",
    "    在Python中，程序在执行的过程中产生的错误称为异常，比如列表索引越界、打开不存在的文件等。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 9.2 异常类\n",
    "    所有异常都是基类Exception的成员，它们都定义在exceptions模块中。\n",
    "    如果这个异常对象没有进行处理和捕捉，程序就会用所谓的回溯（traceback，一种错误信息）终止执行，这些信息包括错误的名称（例如NameError）、原因和错误发生的行号。\n",
    "    NameError：当尝试访问一个不存在的变量时，Python解释器就会抛出该异常。\n",
    "    ZeroDivisionError：当尝试除以0时，Python解释器就会抛出该异常。\n",
    "    SyntaxError：当Python解释器在语法分析时发现语法错误时，就会抛出该异常。\n",
    "    IndexError：当尝试访问一个不存在的索引时，Python解释器就会抛出该异常。\n",
    "    KeyError：当尝试访问一个不存在的键时，Python解释器就会抛出该异常。\n",
    "    FileNotFoundError：当尝试打开一个不存在的文件时，Python解释器就会抛出该异常。\n",
    "    AttributeError：当尝试访问一个不存在的属性时，Python解释"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 9.3 异常处理\n",
    "### 9.3.1 捕获简单异常\n",
    "    try：\n",
    "\t    # 语句块\n",
    "    except：\n",
    "\t    # 异常处理代码"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件123.txt不存在\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('123.txt','r',encoding='utf-8')\n",
    "    print(f.read())\n",
    "except:\n",
    "    print(\"文件123.txt不存在\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T20:03:07.000282Z",
     "end_time": "2024-11-21T20:03:07.093516Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 9.3.2 捕获多个异常\n",
    "    try：\n",
    "    # 语句块\n",
    "    except 异常名称1：\n",
    "    # 异常处理代码1\n",
    "    except异常名称2：\n",
    "    # 异常处理代码\n",
    "    except…"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件123.txt不存在\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('123.txt','r',encoding='utf-8')\n",
    "except FileNotFoundError:\n",
    "    print(\"文件123.txt不存在\")\n",
    "except:\n",
    "    print(\"其他异常\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T20:03:56.044347Z",
     "end_time": "2024-11-21T20:03:56.067829Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 9.3.3 捕获异常的描述信息\n",
    "    当出现多种异常时，为了区分不同的错误信息，可以使用as获取系统反馈的信息"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件123.txt不存在\n",
      "[Errno 2] No such file or directory: '123.txt'\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('123.txt','r',encoding='utf-8')\n",
    "except FileNotFoundError as e:\n",
    "    print(\"文件123.txt不存在\")\n",
    "    print(e)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T20:04:52.025279Z",
     "end_time": "2024-11-21T20:04:52.072417Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 9.3.4 捕获所有的异常\n",
    "    当程序中出现大量异常时，捕获这些异常是非常麻烦的。这时，我们可以在except子句中不指明异常的类型，这样，不管发生何种类型的异常，都会执行except里面的处理代码。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件123.txt不存在\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('123.txt','r',encoding='utf-8')\n",
    "    print(f.read())\n",
    "except:\n",
    "    print(\"文件123.txt不存在\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T20:05:38.767009Z",
     "end_time": "2024-11-21T20:05:38.791209Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 9.3.5 没有捕获到异常\n",
    "    如果try语句没有捕获到任何的错误信息，就不再执行任何except语句，而是会执行else语句。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "该操作执行成功\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('test.txt','r',encoding='utf-8')\n",
    "except:\n",
    "    print(\"文件test.txt不存在\")\n",
    "else:\n",
    "    print(\"该操作执行成功\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-21T20:06:35.032245Z",
     "end_time": "2024-11-21T20:06:35.097583Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 9.3.6 终止行为\n",
    "    在程序中，无论是否捕捉到异常，都必须要执行某件事情，例如关闭文件、释放锁等，这时可以提供finally语句处理。通常情况下，finally用于释放资源。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件123.txt不存在\n",
      "执行了该逻辑\n",
      "hello\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('123.txt','r',encoding='utf-8')\n",
    "except:\n",
    "    print(\"文件123.txt不存在\")\n",
    "else:\n",
    "    print(\"该操作执行成功\")\n",
    "finally:\n",
    "    print(\"执行了该逻辑\")\n",
    "print('hello')"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-20T20:05:30.808164Z",
     "end_time": "2024-11-20T20:05:30.840645Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 10 面向对象程序设计（OOP）（Objected Oriented Programming）\n",
    "## 10.1 类(class)的基本概念\n",
    "### 10.1.1 类和对象"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# 一般类名首字母大写，对象首字母小写\n",
    "class Person:\n",
    "    pass\n",
    "person = Person()"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.1.2 类的构造函数"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "调用了一个构造方法\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self):\n",
    "        print(\"调用了一个构造方法\")\n",
    "person = Person()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-27T19:16:29.074162Z",
     "end_time": "2024-11-27T19:16:29.117069Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.1.3 类的析构（解构）方法"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "调用了一个构造方法\n",
      "调用了一个析构方法\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self):\n",
    "        print(\"调用了一个构造方法\")\n",
    "    def __del__(self):\n",
    "        print(\"调用了一个析构方法\")\n",
    "person = Person()\n",
    "del person"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-27T19:22:35.435519Z",
     "end_time": "2024-11-27T19:22:35.447336Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.1.4 self的使用\n",
    "* 在方法的列表中，第一个参数永远都是self\n",
    "* self的字面意思是自己，我们可以把它当作C++中的this指针来理解，表示的是对象自身\n",
    "* 当某个对象调用方法的时候，Python解释器会把这个对象当作是第一个参数传给self，开发者只需要传递后面的参数就行"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "狗的颜色为黄色\n"
     ]
    }
   ],
   "source": [
    "class Dog:\n",
    "    def __init__(self, newColor):\n",
    "        self.color = newColor\n",
    "    def printColor(self):\n",
    "        print(f\"狗的颜色为{self.color}\")\n",
    "dog = Dog(\"黄色\")\n",
    "dog.printColor()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-27T19:26:12.226963Z",
     "end_time": "2024-11-27T19:26:12.302593Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 10.2 类的封装\n",
    "__封装就是把客观的事物封装成抽象的类，并且类可以把自己的数据和方法只让可信的类或者对象进行操作，对不可信的类进行信息隐藏。简单地说就是：封装使对象的设计者与对象的使用者分开，使用者只要知道对象可以做什么就可以了，不需要知道具体是怎么实现的。封装可以有助于提高类和系统的安全性__"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我正在种地\n",
      "小李\n",
      "18\n",
      "我正在种地\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "        # python类内所有属性都是public\n",
    "    def work(self):\n",
    "        print(\"我正在种地\")\n",
    "laowang = Person(\"老王\", 22)\n",
    "laowang.age = 40\n",
    "laowang.work()\n",
    "xiaoli = Person(\"小李\", 18)\n",
    "print(xiaoli.name)\n",
    "print(xiaoli.age)\n",
    "xiaoli.work()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-27T19:41:19.058347Z",
     "end_time": "2024-11-27T19:41:19.088129Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "人的年龄可以随意设置，显然不合适。\n",
    "为了保护类里面的属性，可以采用如下方式解决：\n",
    "1. 把属性定义为私有属性，即在属性名的前面加上两个下划线；但是，python类中并未有真正的私有属性概念，所以两个下划线的写法知识一种提示的作用\n",
    "2. 添加用于设置或获取属性值的两个方法供外界调用"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "300\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.__age__ = age\n",
    "laowang = Person(\"老王\", 30)\n",
    "laowang.__age__ = 300\n",
    "print(laowang.__age__)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-28T20:00:01.236467Z",
     "end_time": "2024-11-28T20:00:01.253314Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 10.3 类的继承\n",
    "**注意super的用法**\n",
    "1.重写(Override)\n",
    "从字面上看，重写就是 重新写一遍的意思。其实就是在子类中把父类本身有的方法重新写一遍。子类继承了父类原有的方法，但有时子类并不想原封不动的继承父类中的某个方法，所以在方法名，参数列表，返回类型(除过子类中方法的返回值是父类中方法返回值的子类时)都相同的情况下， 对方法体进行修改或重写，这就是重写。但要注意子类函数的访问修饰权限不能少于父类的。\n",
    "2.重载(Overload)\n",
    "在一个类中，同名的方法如果有不同的参数列表（参数类型不同、参数个数不同甚至是参数顺序不同）则视为重载。同时，重载对返回类型没有要求，可以相同也可以不同，但不能通过返回类型是否相同来判断重载。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "小王 18 中国大学\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "# 父类放到括号里\n",
    "class Student(Person):\n",
    "    def __init__(self, name, age, school):\n",
    "        super().__init__(name, age)\n",
    "        self.school = school\n",
    "\n",
    "student = Student(\"小王\", 18, \"中国大学\")\n",
    "print(student.name, student.age, student.school)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-27T19:54:46.753380Z",
     "end_time": "2024-11-27T19:54:46.795797Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 10.4 类的多态\n",
    "**多态的概念：**\n",
    "**在面向对象编程中，如果一个操作针对不同的对象具有不同的实现方式，这个操作就可以被称之为多态。**"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我正在学习\n",
      "我正在讲课\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "class Student(Person):\n",
    "    def __init__(self, name, age):\n",
    "        super().__init__(name, age)\n",
    "    def work(self):\n",
    "        print(\"我正在学习\")\n",
    "\n",
    "class Teacher(Person):\n",
    "    def __init__(self, name, age):\n",
    "        super().__init__(name, age)\n",
    "    def work(self):\n",
    "        print(\"我正在讲课\")\n",
    "\n",
    "def GoTowork(man):\n",
    "    man.work()\n",
    "student = Student(\"小王\", 18)\n",
    "teacher = Teacher(\"老王\", 18)\n",
    "GoTowork(student)\n",
    "GoTowork(teacher)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-27T20:04:19.688405Z",
     "end_time": "2024-11-27T20:04:19.802949Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 10.5 类的属性和实例属性"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "小王 18 1\n",
      "老王 18 老师\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    id = 0\n",
    "\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "class Student(Person):\n",
    "    def __init__(self, name, age, id):\n",
    "        super().__init__(name, age)\n",
    "        self.id = id\n",
    "    def work(self):\n",
    "        print(\"我正在学习\")\n",
    "\n",
    "class Teacher(Person):\n",
    "    def __init__(self, name, age, title):\n",
    "        super().__init__(name, age)\n",
    "        self.title = title\n",
    "    def work(self):\n",
    "        print(\"我正在讲课\")\n",
    "\n",
    "student = Student(\"小王\", 18, 1)\n",
    "teacher = Teacher(\"老王\", 18, \"老师\")\n",
    "print(student.name, student.age, student.id)\n",
    "print(teacher.name, teacher.age, teacher.title)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-11-28T20:02:20.413659Z",
     "end_time": "2024-11-28T20:02:20.502923Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 10.6 类的实例方法、类方法和静态方法\n",
    "### 10.6.1 实例方法\n",
    "    必须实例化后才能使用"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我要工作\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self):\n",
    "        pass\n",
    "\n",
    "    def work(self):\n",
    "        print(\"我要工作\")\n",
    "\n",
    "person = Person()\n",
    "person.work()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:35:35.051859Z",
     "end_time": "2024-12-07T10:35:35.073438Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.6.2 类方法\n",
    "    实不实例化都能使用"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我要工作\n",
      "我要工作\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self):\n",
    "        pass\n",
    "\n",
    "    @classmethod\n",
    "    def work(self):\n",
    "        print(\"我要工作\")\n",
    "\n",
    "Person.work()\n",
    "person = Person()\n",
    "person.work()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:36:27.276248Z",
     "end_time": "2024-12-07T10:36:27.356364Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.6.3 静态方法\n",
    "    一般不进行实例化，直接通过（类名.方法名）的方法使用"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我要工作\n",
      "我要工作\n"
     ]
    }
   ],
   "source": [
    "class Tools:\n",
    "    @staticmethod\n",
    "    def tool():\n",
    "        print(\"我要工作\")\n",
    "\n",
    "Tools.tool()\n",
    "tool = Tools()\n",
    "tool.tool()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:37:22.839176Z",
     "end_time": "2024-12-07T10:37:22.941198Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 10.7. 类的常用特殊方法\n",
    "### 10.7.1 __dir__()方法\n",
    "    dir()方法是 Python 内置的一个非常有用的函数，用于获取对象的属性和方法列表。\n",
    "    基本用法:\n",
    "    1.不带参数调用 dir() 会返回当前作用域内的所有变量和方法名称。\n",
    "    2.带参数调用 dir(object) 会返回指定对象的所有属性和方法名称。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "data": {
      "text/plain": "['work']"
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    def work(self):\n",
    "        pass\n",
    "\n",
    "    def __str__(self):\n",
    "        return \"我是%s,今年%d岁\" % (self.name, self.age)\n",
    "\n",
    "    def __dir__(self):\n",
    "        return [attr for attr in dir(type(self)) if not attr.startswith('_')]\n",
    "        # 加入了if not attr.startswith('_')后，return 只返回被认为是公共的而非私有的属性\n",
    "        # return [\"work方法用于返回工作内容\"]\n",
    "\n",
    "person = Person('老王', 30)\n",
    "dir(person)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:41:18.079740Z",
     "end_time": "2024-12-07T10:41:18.137950Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.7.2 __str__()方法\n",
    "    __str__(self) 方法是 Python 中的一个特殊方法，也被称为字符串表示方法。它用于定义对象的字符串表示形式，使得对象在被 print() 函数调用或在交互式解释器中直接显示时，能够以更易读的方式呈现。\n",
    "    主要用途：\n",
    "        打印对象时的输出:\n",
    "            当您使用 print(obj) 或直接在交互式解释器中输入 obj 时，Python 会自动调用 obj.__str__() 方法来获取对象的字符串表示。\n",
    "        调试和日志记录:\n",
    "            在调试过程中，__str__ 方法可以帮助您更好地理解对象的状态，因为它允许您自定义对象的输出格式。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "张三的年龄是：25\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    def __str__(self):\n",
    "        return \"%s的年龄是：%d\" % (self.name, self.age)\n",
    "\n",
    "\n",
    "person = Person('张三', 25)\n",
    "print(person)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:44:14.542540Z",
     "end_time": "2024-12-07T10:44:14.667613Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<__main__.Person object at 0x0000028A68631850>\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    # def __str__(self):\n",
    "    #     return \"%s的年龄是：%d\" % (self.name, self.age)\n",
    "\n",
    "\n",
    "person = Person('张三', 25)\n",
    "print(person)\n",
    "# 以下表示形式通常在没有定义 __str__ 或 __repr__ 方法时出现"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:44:32.212838Z",
     "end_time": "2024-12-07T10:44:32.304462Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 10.8. Python类的多继承"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "__Python 中的 MRO —— 方法搜索顺序:__\n",
    "    Python 中针对类提供了一个内置属性 __mro__ 可以查看方法搜索顺序\n",
    "    MRO 是 method resolution order，主要用于在多继承时判断 方法、属性的调用路径\n",
    "    print(C.__mro__)  #C是多继承后的类名"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tom male 88\n",
      "这是Human的方法\n",
      "这是我person特有的方法\n",
      "这是Human的方法\n"
     ]
    }
   ],
   "source": [
    "#1.多继承：子类有多个父类\n",
    "\n",
    "class Human:\n",
    "    def __init__(self, sex):\n",
    "        self.sex = sex\n",
    "\n",
    "    def p(self):\n",
    "        print(\"这是Human的方法\")\n",
    "\n",
    "\n",
    "class Person:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "    def p(self):\n",
    "        print(\"这是Person的方法\")\n",
    "\n",
    "    def person(self):\n",
    "        print(\"这是我person特有的方法\")\n",
    "\n",
    "\n",
    "class Teacher(Person):\n",
    "    def __init__(self, name, age):\n",
    "        super().__init__(name)\n",
    "        self.age = age\n",
    "\n",
    "\n",
    "class Student(Human, Person):\n",
    "    def __init__(self, name, sex, grade):\n",
    "    #要想调用特定父类的构造器可以使用父类名.__init__方式。多继承使用super，会有一个坑，具体参考后面\n",
    "       Human.__init__(self,sex)\n",
    "       Person.__init__(self,name)\n",
    "       self.grade = grade\n",
    "\n",
    "\n",
    "class Son(Human, Teacher):\n",
    "    def __init__(self, sex, name, age, fan):\n",
    "        Human.__init__(self, sex)\n",
    "        Teacher.__init__(self, name, age)\n",
    "        self.fan = fan\n",
    "\n",
    "\n",
    "# ------创建对象 -------------\n",
    "stu = Student(\"tom\", \"male\", 88)\n",
    "print(stu.name,stu.sex,stu.grade)\n",
    "stu.p()  # 虽然父类Human和Person都有同名P()方法 ，但是调用的是括号里的第一个父类Human的方法\n",
    "\n",
    "\n",
    "son1 = Son(\"jerry\", \"female\", 18, \"打球\")\n",
    "son1.person()  # 可以调用父类的父类的方法。\n",
    "son1.p()  # 子类调用众多父类中同名的方法，按继承的顺序查找。"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:52:58.140572Z",
     "end_time": "2024-12-07T10:52:58.261285Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "__总结:__\n",
    "    1.需要注意圆括号中继承父类的顺序，若是父类中有相同的方法名，而在子类使用时未指定，python从左至右搜索 即方法在子类中未找到时，从左到右查找父类中是否包含方法\n",
    "    2.支持多层父类继承，子类会继承父类所有的属性和方法，包括父类的父类的所有属性和方法。\n"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "__多继承的使用注意事项:__"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这是Human的方法\n",
      "this sisex\n"
     ]
    }
   ],
   "source": [
    "#1.多继承子类对父类构造方法的调用\n",
    "class Human:\n",
    "    def __init__(self,sex):\n",
    "        self.sex = sex\n",
    "    def p(self):\n",
    "        print(\"这是Human的方法\")\n",
    "    def str1(self):\n",
    "        print(\"this si\"+str(self.sex))\n",
    "\n",
    "class Person:\n",
    "    def __init__(self,name):\n",
    "        self.name = name\n",
    "    def p(self):\n",
    "        print(\"这是Person的方法\")\n",
    "    def person(self):\n",
    "        print(\"这是我person特有的方法\")\n",
    "\n",
    "    def str2(self):\n",
    "        print( \"this is:\" + str(self.name))\n",
    "\n",
    "class Student(Human,Person): #注意子类如果没有构造方法时，按括号内父类的继承顺序去继承父类构造方法，只继承一个\n",
    "    def prin(self):\n",
    "        print(\"student\")\n",
    "#------创建对象 -------------\n",
    "#stu1=Studnent(\"男\",\"tom\")报错。\n",
    "stu = Student(\"sex\") #这里继承的是Human的构造方法。\n",
    "stu.p()\n",
    "stu.str1()\n",
    "#stu.str2()报错，因为即使human和person都是一个参数的构造方法，但是这里继承调用的是第一个Human的构造方法"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:54:34.444863Z",
     "end_time": "2024-12-07T10:54:34.488709Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "__总结:__\n",
    "    子类从多个父类派生，而子类又没有自己的构造函数时:\n",
    "    1.按顺序继承，哪个父类在最前面且它又有自己的构造函数，就继承它的构造函数；\n",
    "    2.如果最前面第一个父类没有构造函数，则继承第2个的构造函数，第2个没有的话，再往后找，以此类推。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "__多继承时使用super调用父类属性方法的注意事项:__\n",
    "    不使用super调用父类方法，使用父类名.方法名的形式。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(<class '__main__.Grandson'>, <class '__main__.Son1'>, <class '__main__.Son2'>, <class '__main__.Parent'>, <class 'object'>)\n",
      "Grandson的init开始被调用\n",
      "Son1的init开始被调用\n",
      "Son2的init开始被调用\n",
      "parent的init开始被调用\n",
      "parent的init结束被调用\n",
      "Son2的init结束被调用\n",
      "Son1的init结束被调用\n",
      "Grandson的init结束被调用\n",
      "姓名： grandson\n",
      "年龄： 12\n",
      "性别： 男\n"
     ]
    }
   ],
   "source": [
    "class Parent(object):\n",
    "    def __init__(self, name, *args, **kwargs):  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('parent的init开始被调用')\n",
    "        self.name = name\n",
    "        print('parent的init结束被调用')\n",
    "\n",
    "class Son1(Parent):\n",
    "    def __init__(self, name, age, *args, **kwargs):  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('Son1的init开始被调用')\n",
    "        self.age = age\n",
    "        super().__init__(name, *args, **kwargs)  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('Son1的init结束被调用')\n",
    "\n",
    "class Son2(Parent):\n",
    "    def __init__(self, name, gender, *args, **kwargs):  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('Son2的init开始被调用')\n",
    "        self.gender = gender\n",
    "        super().__init__(name, *args, **kwargs)  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('Son2的init结束被调用')\n",
    "\n",
    "class Grandson(Son1, Son2):\n",
    "    def __init__(self, name, age, gender):\n",
    "        print('Grandson的init开始被调用')\n",
    "        # 多继承时，相对于使用类名.__init__方法，要把每个父类全部写一遍\n",
    "        # 而super只用一句话，执行了全部父类的方法，这也是为何多继承需要全部传参的一个原因\n",
    "        # super(Grandson, self).__init__(name, age, gender) 效果和下面的一样\n",
    "        super().__init__(name, age, gender)\n",
    "        print('Grandson的init结束被调用')\n",
    "\n",
    "print(Grandson.__mro__) #搜索顺序\n",
    "\n",
    "gs = Grandson('grandson', 12, '男')\n",
    "\n",
    "print('姓名：', gs.name)\n",
    "print('年龄：', gs.age)\n",
    "print('性别：', gs.gender)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T10:59:53.215193Z",
     "end_time": "2024-12-07T10:59:53.283641Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "__注意:__ 上面代码里当在子类中通过父类名调用时，parent被执行了2次"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "使用super调用父类中的方法，注意分析程序的执行顺序。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "class Parent(object):\n",
    "    def __init__(self, name, *args, **kwargs):  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('parent的init开始被调用')\n",
    "        self.name = name\n",
    "        print('parent的init结束被调用')\n",
    "\n",
    "class Son1(Parent):\n",
    "    def __init__(self, name, age, *args, **kwargs):  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('Son1的init开始被调用')\n",
    "        self.age = age\n",
    "        super().__init__(name, *args, **kwargs)  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('Son1的init结束被调用')\n",
    "\n",
    "class Son2(Parent):\n",
    "    def __init__(self, name, gender, *args, **kwargs):  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('Son2的init开始被调用')\n",
    "        self.gender = gender\n",
    "        super().__init__(name, *args, **kwargs)  # 为避免多继承报错，使用不定长参数，接受参数\n",
    "        print('Son2的init结束被调用')\n",
    "\n",
    "class Grandson(Son1, Son2):\n",
    "    def __init__(self, name, age, gender):\n",
    "        print('Grandson的init开始被调用')\n",
    "        # 多继承时，相对于使用类名.__init__方法，要把每个父类全部写一遍\n",
    "        # 而super只用一句话，执行了全部父类的方法，这也是为何多继承需要全部传参的一个原因\n",
    "        # super(Grandson, self).__init__(name, age, gender) 效果和下面的一样\n",
    "        super().__init__(name, age, gender)\n",
    "        print('Grandson的init结束被调用')\n",
    "\n",
    "print(Grandson.__mro__) #搜索顺序\n",
    "\n",
    "gs = Grandson('grandson', 12, '男')\n",
    "\n",
    "print('姓名：', gs.name)\n",
    "print('年龄：', gs.age)\n",
    "print('性别：', gs.gender)"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "__注意:__\n",
    "    在上面模块中，当在子类中通过super调用父类方法时，parent被执行了1次。\n",
    "__super调用过程:__\n",
    "    上面gs初始化时，先执行grandson中init方法, 其中的init有super调用，每执行到一次super时，都会从__mro__方法元组中顺序查找搜索。所以先调用son1的init方法，在son1中又有super调用，这个时候就就根据__mro__表去调用son2的init，然后在son2中又有super调用，这个就根据mro表又去调用parent中的init，直到调用object中的init.  所以上面的打印结果如此，要仔细分析执行过程。\n",
    "__尖叫提示:__\n",
    "    1.super().__init__相对于类名.__init__，在单继承上用法基本无差\n",
    "    2.但在多继承上有区别，super方法能保证每个父类的方法只会执行一次，而使用类名的方法会导致方法被执行多次，具体看前面的输出结果\n",
    "    3.多继承时，使用super方法，对父类的传参数，应该是由于python中super的算法导致的原因，必须把参数全部传递，否则会报错\n",
    "    4.单继承时，使用super方法，则不能全部传递，只能传父类方法所需的参数，否则会报错\n",
    "    5.多继承时，相对于使用类名.__init__方法，要把每个父类全部写一遍, 而使用super方法，只需写一句话便执行了全部父类的方法，这也是为何多继承需要全部传参的一个原因"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "单继承使用super调用父类方法"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Grandson的init开始被调用\n",
      "Son1的init开始被调用\n",
      "parent的init开始被调用\n",
      "parent的init结束被调用\n",
      "Son1的init结束被调用\n",
      "Grandson的init结束被调用\n",
      "姓名： grandson\n",
      "年龄： 12\n"
     ]
    }
   ],
   "source": [
    "class Parent(object):\n",
    "    def __init__(self, name):\n",
    "        print('parent的init开始被调用')\n",
    "        self.name = name\n",
    "        print('parent的init结束被调用')\n",
    "\n",
    "class Son1(Parent):\n",
    "    def __init__(self, name, age):\n",
    "        print('Son1的init开始被调用')\n",
    "        self.age = age\n",
    "        super().__init__(name)  # 单继承不能提供全部参数\n",
    "        print('Son1的init结束被调用')\n",
    "\n",
    "class Grandson(Son1):\n",
    "    def __init__(self, name, age, gender):\n",
    "        print('Grandson的init开始被调用')\n",
    "        super().__init__(name, age)  # 单继承不能提供全部参数\n",
    "        print('Grandson的init结束被调用')\n",
    "\n",
    "gs = Grandson('grandson', 12, '男')\n",
    "print('姓名：', gs.name)\n",
    "print('年龄：', gs.age)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T11:06:47.602478Z",
     "end_time": "2024-12-07T11:06:47.697039Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 10.9 Python泛型\n",
    "在Python中，\"泛型\"（Generics）是指可以在定义类、函数或方法时指定可变类型的机制。这样可以提高代码的重用性和灵活性。Python 3.5 引入了 typing 模块来支持类型提示，其中包括对泛型的支持。\n",
    "__泛型的基本概念:__\n",
    "类型变量：使用 TypeVar 定义一个类型变量，可以在泛型类或函数中使用。\n",
    "泛型类：使用 Generic 类来定义泛型类。\n",
    "泛型函数：使用类型变量来定义泛型函数。"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.9.1 类型变量"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "from typing import TypeVar, Generic\n",
    "\n",
    "T = TypeVar('T')  # T 是一个类型变量"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.9.2 泛型类"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "Hello\n"
     ]
    }
   ],
   "source": [
    "class Box(Generic[T]):\n",
    "    def __init__(self, content: T):\n",
    "        self.content = content\n",
    "\n",
    "    def get_content(self) -> T:\n",
    "        return self.content\n",
    "\n",
    "# 使用泛型类\n",
    "box1 = Box[int](10)\n",
    "box2 = Box[str](\"Hello\")\n",
    "\n",
    "print(box1.get_content())  # 输出: 10\n",
    "print(box2.get_content())  # 输出: Hello"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T11:10:31.410914Z",
     "end_time": "2024-12-07T11:10:31.456772Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.9.3 泛型函数"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "apple\n"
     ]
    }
   ],
   "source": [
    "from typing import TypeVar, List\n",
    "T = TypeVar('T')\n",
    "\n",
    "def first_element(lst: List[T]) -> T:\n",
    "    return lst[0]\n",
    "\n",
    "# 使用泛型函数\n",
    "numbers = [1, 2, 3]\n",
    "words = [\"apple\", \"banana\", \"cherry\"]\n",
    "\n",
    "print(first_element(numbers))  # 输出: 1\n",
    "print(first_element(words))    # 输出: apple"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T11:10:28.888521Z",
     "end_time": "2024-12-07T11:10:28.920822Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 10.9.4 泛型的限制约束"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [],
   "source": [
    "from typing import TypeVar, Generic\n",
    "\n",
    "T = TypeVar('T', int, str)  # T 只能是 int 或 str\n",
    "\n",
    "class LimitedBox(Generic[T]):\n",
    "    def __init__(self, content: T):\n",
    "        self.content = content\n",
    "\n",
    "    def get_content(self) -> T:\n",
    "        return self.content\n",
    "\n",
    "# 使用泛型类\n",
    "box1 = LimitedBox[int](10)\n",
    "box2 = LimitedBox[str](\"Hello\")\n",
    "\n",
    "# 以下会引发类型检查错误\n",
    "# box3 = LimitedBox[float](3.14)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-12-07T11:10:25.444348Z",
     "end_time": "2024-12-07T11:10:25.568949Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "__总结:__\n",
    "    泛型是Python类型系统的一个强大特性，它允许你在编写代码时更灵活地处理不同类型的数据，同时保持类型安全。通过使用 TypeVar 和 Generic，你可以创建泛型类和泛型函数，从而提高代码的可重用性和可维护性。"
   ],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
